<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加规格</title>
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/layui@2.6.8/dist/css/layui.css">
    <script src="//cdn.jsdelivr.net/npm/layui@2.6.8/dist/layui.js" charset="utf-8"></script>
</head>

<body>
    <div style="margin: 15px;padding: 15px;background-color: #fff;">
        <div style="text-align: right;">
            <a class="layui-btn layui-btn-xs layui-btn-primary" href="/admins/products/skus?pro_id={$pro_id}">返回</a>
        </div>
        <!-- form -->
        <div class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">类目</label>
                <!-- 无限层级联动下拉框 -->
                <div id="cid">
                    <!-- 一级联动 -->
                    <div class="layui-input-inline">
                        <select lay-filter="filter-cate" lay-verify="required" lay-search="">
                            <option></option>
                            {foreach $parent as $cate}
                            <option value="{$cate['id']}">{$cate['title']}</option>
                            {/foreach}
                        </select>
                    </div>
                </div>
            </div>

            <!-- 联动属性 -->
            <div id="propertys"></div>

            <!-- 联动表格 -->
            <table class="layui-table">
                <thead>
                    <tr id="sku-ths">
                        <th>规格名称</th>
                        <th>价格</th>
                        <th>库存</th>
                        <th>状态</th>
                    </tr>
                </thead>

                <tbody id="sku-data">
                </tbody>

            </table>

            <div class="layui-form-item">
                <button class="layui-btn" lay-submit lay-filter="save">保存</button>
            </div>
        </div>

    </div>

    <script>
        layui.use(['form', 'table'], function () {
            var form = layui.form
                , table = layui.table
                , $ = layui.jquery;

            // 保存
            form.on('submit(save)', function (data) {
                $.post('/admins/products/save_sku', data.field, function (res) {
                    if (res.code) return layer.alert(res.msg, { icon: 2 });
                    layer.alert(res.msg, { icon: 1 });
                    setTimeout(() => window.location.reload(), 1000);
                }, 'json');
            });

            // ajax层级联动类目，属性
            form.on('select(filter-cate)', function (obj) {
                // 重选移除原来的层级联动
                $(obj.othis).parent().nextAll().remove();
                $('#propertys').html(null);
                // 重选生成下级联动
                var pid = obj.value, html = '';
                pid && $.get('/admins/products/add_sku', { pid }, function (res) {
                    if (res.code) return layer.msg(res.msg);
                    // 联动类目
                    if (res.data && res.data.length) {
                        html = '<div class="layui-input-inline">';
                        html += '<select lay-filter="filter-cate" lay-search="">';
                        html += '<option></option>';
                        res.data.forEach(el => html += '<option value="' + el.id + '">' + el.title + '</option>');
                        html += '</select>';
                        html += '</div>';
                        document.getElementById('cid').insertAdjacentHTML('beforeend', html);
                        form.render('select');
                    }
                    // 联动属性
                    if (res.propertys && res.propertys.length) {
                        res.propertys.forEach(el => {
                            html = '<div class="layui-form-item sku-propertys">';
                            html += '<label class="layui-form-label" name_id="' + el.id + '">' + el.title + '</label>';
                            html += '<div class="layui-input-block">';
                            el.values.forEach(ele => html += '<input type="checkbox" name_id="' + ele.name_id + '" value_id="' + ele.id + '" title="' + ele.title + '" lay-filter="filter-property" lay-skin="primary">');
                            html += '</div>';
                            html += '</div>';
                            document.getElementById('propertys').insertAdjacentHTML('beforeend', html);
                        });
                        form.render('checkbox');
                    }
                }, 'json');
            });

            // ajax属性联动规格
            form.on('checkbox(filter-property)', function (obj) {
                var propertys_chks = [];
                $('#sku-ths .sku').remove();
                $('#sku-data').html(null);
                $('#propertys .sku-propertys').each(function (i, el) {
                    var chkArr = [];
                    var chkTits = [];
                    var chks = $(el).find('input[type="checkbox"]:checked').each(function (j, ele) {
                        chkArr.push(ele.getAttribute('value_id'));
                        chkTits[ele.getAttribute('value_id')] = ele.getAttribute('title');
                    });
                    if (chkArr.length > 0) {
                        propertys_chks.push({
                            title: $(el).children('label').text(),
                            name_id: $(el).children('label').attr('name_id'),
                            values: chkArr,
                            titles: chkTits,
                        });
                    }
                    if (chkArr.length == 0) {
                        var name_id = $(obj.othis).parent().siblings('label').attr('name_id');
                        propertys_chks.forEach((item, i) => {
                            if (item.name_id == name_id) propertys_chks.slice(i, 1);
                        });
                    }
                });

                // sku数据
                var skuArray = [];
                var skuList = [];
                if (propertys_chks.length) {
                    propertys_chks.forEach(el => el.values.length && skuArray.push(el.values));
                    if (skuArray.length) {
                        skuList = skuArray.reduce((prev, curr) => {
                            var res = [];
                            prev.forEach(p => curr.forEach(c => res.push(p.concat([c]))));
                            return res;
                        }, [[]]);
                    }

                    // 渲染表头字段
                    propertys_chks.reverse().forEach(el => document.getElementById('sku-ths').insertAdjacentHTML('afterbegin', '<th class="sku">' + el.title + '</th>'));

                    // 渲染表格主体
                    if (skuList.length) {
                        skuList.forEach((el, i) => {
                            var tr = '<tr>';
                            el.forEach(elem => {
                                var property = propertys_chks.filter(item => -1 !== item.values.indexOf(elem)).pop();
                                tr += '<td><input type="hidden" name="name_value[' + i + '][' + property['name_id'] + ']" value="' + elem + '">' + property['titles'][elem] + '</td>';
                            });
                            tr += '<td><input type="text" name="sku_title[' + i + ']" value="" lay-verify="required" class="layui-input"></td>';
                            tr += '<td><input type="text" name="price[' + i + ']" value="" lay-verify="required" class="layui-input"></td>';
                            tr += '<td><input type="text" name="stock[' + i + ']" value="" lay-verify="required" class="layui-input"></td>';
                            tr += '<td><input type="hidden" name="status[' + i + ']" value="0"><input type="checkbox" name="status[' + i + ']" value="1" title="下架" lay-skin="primary"></td>';
                            tr += '</tr>';
                            document.getElementById('sku-data').insertAdjacentHTML('beforeend', tr);
                        });
                    }

                }

                form.render('checkbox');
            });

            // 保存
            form.on('submit(save)', function (obj) {
                var pro_id = '{$pro_id}';
                $.post('/admins/products/save_pro_sku?pro_id=' + pro_id, obj.field, function (res) {
                    if (res.code) return layer.alert(res.msg, { icon: 2 });
                    layer.alert(res.msg, { icon: 1 });
                    setTimeout(() => window.location.href = "/admins/products/skus?pro_id="+ pro_id, 1000)
                }, 'json');
            });
        });
    </script>
</body>

</html>